﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using Microsoft.Web.Helpers;
using VideoSeller.Business.Data.Entities;
using VideoSeller.Business.Data.Enums;
using VideoSeller.Business.Data.Json;
using VideoSeller.Business.JavaScriptConverters;
using VideoSeller.Business.Models;
using VideoSeller.Core.Interfaces;
using VideoSeller.Web.Models;

namespace VideoSeller.Web.Controllers
{
	[Authorize]
	public class AjaxController : BaseController
	{
		private readonly SettingsModel _settingsModel;
		private readonly CategoryModel _categoryModel;
		private readonly OnlineContentModel _onlineContentModel;
		private readonly OnlineRatingModel _onlineRatingModel;
		private readonly ResourceModel _resourceModel;
		private readonly WaitModel _waitModel;
		private readonly PostingModel _postingModel;
		private readonly PaidModel _paidModel;
		private readonly TeamChatModel _teamChatModel;
		private readonly IDatabaseSettingsProvider _databaseSettingsProvider;
        private readonly OnlineContentClaimModel _onlineContentClaimModel;
		private readonly CountryModel _countryModel;
        private readonly MailModel _mailModel;
        private readonly BonusFinanceModel _bonusFinanceModel;

		public AjaxController(SettingsModel settingsModel, CategoryModel categoryModel, CountryModel countryModel,
            OnlineContentModel onlineContentModel, OnlineRatingModel onlineRatingModel, 
            ResourceModel resourceModel, WaitModel waitModel, IDatabaseSettingsProvider databaseSettingsProvider,
            PostingModel postingModel, PaidModel paidModel, TeamChatModel teamChatModel, OnlineContentClaimModel onlineContentClaimModel, 
            MailModel mailModel, BonusFinanceModel bonusFinanceModel)
		{
			_settingsModel = settingsModel;
			_categoryModel = categoryModel;
			_onlineContentModel = onlineContentModel;
			_onlineRatingModel = onlineRatingModel;
			_resourceModel = resourceModel;
			_waitModel = waitModel;
			_postingModel = postingModel;
			_databaseSettingsProvider = databaseSettingsProvider;
			_paidModel = paidModel;
			_teamChatModel = teamChatModel;
            _onlineContentClaimModel = onlineContentClaimModel;
			_countryModel = countryModel;
            _mailModel = mailModel;
            _bonusFinanceModel = bonusFinanceModel;

		}

		[HttpGet]
		[AllowAnonymous]
		public JsonResult IsLoginExists(string login)
		{
			if (Request.IsAjaxRequest())
			{
				if (Membership.GetUser(login) != null)
				{
					return Json(true, JsonRequestBehavior.AllowGet);
				}
			}

			return Json(false, JsonRequestBehavior.AllowGet);
		}

		[HttpGet]
		[AllowAnonymous]
		public JsonResult IsEmailExists(string email)
		{
			if (Request.IsAjaxRequest())
			{
				if (Membership.FindUsersByEmail(email).Count > 0)
				{
					return Json(true, JsonRequestBehavior.AllowGet);
				}
			}

			return Json(false, JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult HasMoneyToMeeting(int personsInMeeting)
		{
			if (Request.IsAjaxRequest())
			{
				var total = CurrentClient.Finance.Total;
				var price = _databaseSettingsProvider.MeetingPriceForMember*personsInMeeting;

				if (total >= price)
				{
					return Json(true, JsonRequestBehavior.AllowGet);
				}
			}

			return Json(false, JsonRequestBehavior.AllowGet);
		}
        [HttpPost]
        public JsonResult PayForContentPublish(int onlineContentId)
        {
            Business.Data.OnlineContent oc = _onlineContentModel.GetOnlineContent(onlineContentId);
            if (oc == null)
                return Json("NF", JsonRequestBehavior.AllowGet);
            if (oc.NeedMoney > 0)
            {
                if (CurrentClient.Finance.Total > oc.NeedMoney)
                {
                    _postingModel.PayForContentPublish(CurrentClient.Finance, oc.NeedMoney, onlineContentId);
                    _onlineContentModel.clearNeedMoney(onlineContentId);
                    return Json("YP", JsonRequestBehavior.AllowGet);
                }
                else
                    return Json("NM", JsonRequestBehavior.AllowGet);
            }
            else
                return Json("YA", JsonRequestBehavior.AllowGet);
        }
		[HttpPost]
		public JsonResult PayForContent(int onlineContentId)
		{
			if (Request.IsAjaxRequest())
			{
				
                decimal bonus = 0;
				var onlineContent = _onlineContentModel.GetOnlineContent(onlineContentId);
//
				if (onlineContent != null)
				{
                    if (onlineContent.MinimalPrice.HasValue)
                    {
                        bonus = _bonusFinanceModel.GetMany(CurrentClient.UserId, onlineContent.MinimalPrice.Value);
                        if (bonus > 0)
                            _postingModel.AddFinanceOperation(CurrentClient.UserId, bonus, FinanceOperation.AdministratorAdd,"for content "+ onlineContent.Id.ToString());

                    }
                    var total = CurrentClient.Finance.Total;
					if (onlineContent.MinimalPrice.HasValue && total >= onlineContent.MinimalPrice.Value)
					{
                        if (bonus > 0)
						    _postingModel.AddFinanceOperation(CurrentClient.UserId, onlineContent.MinimalPrice.Value, FinanceOperation.OnlineContentPayment);
                        else
                            _postingModel.AddFinanceOperation(CurrentClient.UserId, onlineContent.MinimalPrice.Value, FinanceOperation.OnlineContentPayment, bonus.ToString());
						_paidModel.Pay(onlineContentId, CurrentClient.UserId, onlineContent.MinimalPrice.Value, bonus);
                        if (bonus > 0)
                            _postingModel.AddFinanceOperation(onlineContent.UserId, onlineContent.MinimalPrice.Value, FinanceOperation.OnlineContentRecharge);
                        else
                            _postingModel.AddFinanceOperation(onlineContent.UserId, onlineContent.MinimalPrice.Value, FinanceOperation.OnlineContentRecharge, bonus.ToString());

						return Json("paid", JsonRequestBehavior.AllowGet);
					}

					return Json("money", JsonRequestBehavior.AllowGet);
				}
			}

			return Json("failed", JsonRequestBehavior.AllowGet);
		}

		[HttpGet]
		public PartialViewResult WizardOnlineStep(int step)
		{
			var model = new OnlineViewModel();
            int ret=0;
            decimal dret = 0;
            model.MaxPriceConferenceVSM = 10000;
            model.MaxPriceMyVSM = 1000;
            model.MaxPriceMeetingVSM = 100000;
            model.MinViewCounterForSetPrice = 1000;
            model.BasicPublishPrice = 10;
            if (int.TryParse(_settingsModel.GetSetting("MaxPriceMeetingVSM").Value, out ret))
                model.MaxPriceMeetingVSM = ret;
            if (int.TryParse(_settingsModel.GetSetting("MaxPriceConferenceVSM").Value, out ret))
                model.MaxPriceConferenceVSM = ret;
            try
            {
                if (decimal.TryParse(_settingsModel.GetSetting("BasicPublishPrice").Value, out dret))
                    model.BasicPublishPrice = dret;
            }
            catch
            {
            }
            if (int.TryParse(_settingsModel.GetSetting("MaxPriceMyVSM").Value, out ret))
                model.MaxPriceMyVSM = ret;
            if (int.TryParse(_settingsModel.GetSetting("MinViewCounterForSetPrice").Value, out ret))
                model.MinViewCounterForSetPrice = ret;
            model.CurViewCounterForSetPrice = CurrentClient.OnlineContents.Sum(m => m.Views_online);
            if (step == 0)
            {
                model.QualityStringCosts = _settingsModel.QualityStringCosts;
              model.MaxViewerCntMult=  _settingsModel.MaxViewerCntMult;
              model.MaxTimeMult = _settingsModel.MaxTimeMult;
              model.ContentTypeMult = _settingsModel.ContentTypeMult;
              model.manyUser = (model.CurrentMembershipUser.Client.Finance != null) ? model.CurrentMembershipUser.Client.Finance.Total : 0; 
            }
			if (step == 1)
			{
				var cultures = _resourceModel.GetUniqueCultureInfos().OrderBy(x => x.DisplayName);
                model.Cultures.AddRange(cultures.Select(x => new CultureItemViewModel { Value = x.Name, Text = x.NativeName.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0].Split(new[] { "(" }, StringSplitOptions.RemoveEmptyEntries)[0], Image = Url.Content(string.Format("~/Content/images/lang_{0}_small.png", x.Name)) }));
				model.Countries = _countryModel.GetAll().OrderBy(x => x.Name);
			}
			else if (step == 2)
			{
				model.Categories = _categoryModel.GetCategories();
			}
			else if (step == 5)
			{
				model.MembersCountList = _settingsModel.GetMembersCountList();
				model.MeetingPriceForMember = _databaseSettingsProvider.MeetingPriceForMember;
			}

			return PartialView(string.Format("~/Views/Wizard/Online/Step{0}.cshtml", step), model);
		}

		[HttpPost]
		public JsonResult SaveOnlineContent(string content)
		{
			if (Request.IsAjaxRequest())
			{
				var serializer = new JavaScriptSerializer();
				serializer.RegisterConverters(new List<JavaScriptConverter> {new OnlineContentConverter()});
				var onlineContentItem = serializer.Deserialize<OnlineContentItem>(content);

				if (onlineContentItem != null)
				{
					if (onlineContentItem.CreatedContentId > 0)
					{
						_onlineContentModel.UpdateOnlineContent(onlineContentItem, CurrentClient.UserId);
						return Json(onlineContentItem.CreatedContentId, JsonRequestBehavior.AllowGet);
					}

					var itemId = _onlineContentModel.AddOnlineContent(onlineContentItem, CurrentClient.UserId);
					if (onlineContentItem.VideoContentType == VideoContentType.PaidGroups && onlineContentItem.RemoveAds)
					{
						_postingModel.PayForMeeting(CurrentClient.Finance, onlineContentItem.TeamCount);
					}
					return Json(itemId, JsonRequestBehavior.AllowGet);
				}
			}

			return Json(-1, JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult GetOnlineContent(int onlineContentId)
		{
			if (Request.IsAjaxRequest())
			{
				var onlineContentItem = _onlineContentModel.GetOnlineContent(onlineContentId);

				if (onlineContentItem != null)
				{
					var serializer = new JavaScriptSerializer();
					serializer.RegisterConverters(new List<JavaScriptConverter> { new OnlineContentConverter() });
					var json = serializer.Serialize(onlineContentItem);
					return Json(json, JsonRequestBehavior.AllowGet);
				}
			}

			return Json(-1, JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public string UploadOnlineThumbnailImage(HttpPostedFileBase thumbnail)
		{
			if (thumbnail.ContentLength > 0)
			{
				var imageId = Guid.NewGuid();
				var image = new WebImage(thumbnail.InputStream);
				var smallImage = image.Clone().Resize(240, 240);
				var bigImage = image.Clone().Resize(800, 800);
				var ext = Path.GetExtension(thumbnail.FileName);

				var smallUrl = string.Format("~/Upload/OnlineContent/{0}_{1}{2}", imageId, ThumbnailImageSize.Small, ext);
				smallImage.Save(ControllerContext.HttpContext.Server.MapPath(smallUrl));

				var bigUrl = string.Format("~/Upload/OnlineContent/{0}_{1}{2}", imageId, ThumbnailImageSize.Large, ext);
				bigImage.Save(ControllerContext.HttpContext.Server.MapPath(bigUrl));

				return string.Format("~/Upload/OnlineContent/{0}{1}", imageId, ext);
			}

			return string.Empty;
		}

		[HttpPost]
		public string UploadOnlineTeamDocs(HttpPostedFileBase docs)
		{
			if (docs.ContentLength > 0)
			{
				var ext = Path.GetExtension(docs.FileName);
				var relUrl = string.Format("~/Upload/OnlineContent/{0}{1}", Guid.NewGuid(), ext);
				var serverPath = ControllerContext.HttpContext.Server.MapPath(relUrl);
				docs.SaveAs(serverPath);
				return relUrl;
			}

			return string.Empty;
		}

		[HttpPost]
		public JsonResult RateOnlineContent(int onlineContentId, bool positive)
		{
			if (Request.IsAjaxRequest())
			{
				var newRate = _onlineRatingModel.Rate(CurrentClient.UserId, onlineContentId, positive, string.Empty);
				return Json(newRate, JsonRequestBehavior.AllowGet);
			}

			return Json(string.Empty, JsonRequestBehavior.AllowGet);
		}


        [HttpPost]
        public JsonResult DeleteContent(int onlineContentId)
        {
            if (Request.IsAjaxRequest())
            {
                _onlineContentModel.DeleteContent(onlineContentId);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        [HttpPost]
        public JsonResult isStatusChanged(int onlineContentId, String _status)
        {
            string[] ret = null;
            if (Request.IsAjaxRequest())
            {
                ret = _onlineContentModel.isStatusChanged(onlineContentId, _status);
             
            }
            return Json(ret, JsonRequestBehavior.AllowGet);
        }

		[HttpPost]
		public JsonResult MarkOnlineContent(int onlineContentId, bool marked)
		{
			_waitModel.MarkOnlineContent(onlineContentId, CurrentClient.UserId, !marked);

			return Json(string.Empty, JsonRequestBehavior.AllowGet);
		}

		[AllowAnonymous]
        [HttpPost]
        public JsonResult CheckPasswordContent(int onlineContentId, String password)
        {
       
            if (String.IsNullOrEmpty(_onlineContentModel.GetOnlineContent(onlineContentId).Password))
                return Json("false", JsonRequestBehavior.AllowGet);
            if (password == _onlineContentModel.GetOnlineContent(onlineContentId).Password)
                return Json("true", JsonRequestBehavior.AllowGet);
            else
                return Json("false", JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult setContentDsc(int onlineContentId, String dsctext)
        {
            _onlineContentModel.setContentDsc(onlineContentId, dsctext);
             return Json(String.Empty, JsonRequestBehavior.AllowGet);
       
        }

		[HttpPost]
		public JsonResult AddChatMessage(int id, string message, bool? newMessage)
		{
			if (Request.IsAjaxRequest())
			{
				if (!string.IsNullOrEmpty(message) && newMessage.HasValue && newMessage.Value)
				{
					_teamChatModel.AddNewMessage(id, CurrentClient.UserId, message);
				}

				var serializer = new JavaScriptSerializer();
				var items = _teamChatModel.GetChat(id).Select(x => new JChatItem
					{
						DateTime = x.CreateTime.ToString("HH:mm"),
						//HPN
                        //Name =  x.Client.sFirstName ?  HttpContext.GetGlobalResourceObject("Common", "HiddenByOwner", CultureInfo.CurrentUICulture).ToString() : x.Client.FullName ,
                        Name =  x.Client.Login,
						Message = x.Message,
						Url = Url.Action("Profile", "Client", new {id = x.UserId})
					}).ToList();

				return Json(serializer.Serialize(items), JsonRequestBehavior.AllowGet);
			}

			return Json(string.Empty, JsonRequestBehavior.AllowGet);
		}
        [HttpPost]
        public JsonResult AddCommentsMessage(int id, bool isLike, string text)
        {
            if (Request.IsAjaxRequest())
            {
                int rt = 0;
                try
                {
                   rt = _onlineRatingModel.Rate(CurrentClient.UserId, id, isLike, text);
                   if (rt == 0) return Json(String.Empty, JsonRequestBehavior.AllowGet);
                   return Json(rt.ToString(), JsonRequestBehavior.AllowGet);
                }
                catch                 {
                    return Json(String.Empty, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

		[HttpPost]
		public JsonResult AddClaim(int onlineContentId, String userId)
		{
			if (Request.IsAjaxRequest())
			{
                int ret = _onlineContentClaimModel.SetClimeFromUser(onlineContentId,userId);
                    return Json(ret, JsonRequestBehavior.AllowGet);
			}
			return Json(string.Empty, JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult ValidateReCaptcha(string challenge, string response)
		{
			if (Request.IsAjaxRequest())
			{
				var httpWReq = (HttpWebRequest) WebRequest.Create("http://www.google.com/recaptcha/api/verify");
				var encoding = new UTF8Encoding();
				var postData = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", ReCaptcha.PrivateKey, "", challenge, response);
				var data = encoding.GetBytes(postData);

				httpWReq.Method = "POST";
				httpWReq.ContentType = "application/x-www-form-urlencoded";
				httpWReq.ContentLength = data.Length;

				using (var stream = httpWReq.GetRequestStream())
				{
					stream.Write(data, 0, data.Length);
				}

				var httpWRes = (HttpWebResponse)httpWReq.GetResponse();
				var responseString = new StreamReader(httpWRes.GetResponseStream()).ReadToEnd();

				return Json(responseString, JsonRequestBehavior.AllowGet);
			}

			return Json(string.Empty, JsonRequestBehavior.AllowGet);
		}
        [HttpPost]
        public JsonResult SendInvitations(string text, string toList)
        {
            if (Request.IsAjaxRequest())
            {
              ////  this.
               //// MailModel _mailModel = new MailModel(
                int ret = _mailModel.SendInvitation(text, toList, CurrentClient.FullName);
                return Json(ret, JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        [HttpPost]
        public JsonResult addView(String onlineContentId, String userId, String tp)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    object o = HttpContext.Session["LastAddView"];
                    if (o != null && o.ToString() == onlineContentId)
                        return Json("", JsonRequestBehavior.AllowGet);
                    //
                    HttpContext.Session["LastAddView"] = onlineContentId;
                }
                catch
                { }
                _onlineContentModel.addView(onlineContentId, userId, tp);
                return Json("", JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult cancelPublishing(String onlineContentId)
        {
            if (Request.IsAjaxRequest())
            {
                _onlineContentModel.cancelPublishing(onlineContentId);
                return Json("", JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        
	}
}